<template>
  <div class="detail_wrap">
    <div class="flex mb10 flex_h_between">
      <div class="info_text cursor" @click="back"><a-icon type="left" />返回</div>
      <!-- <p @click="toSignList" class="info_text cursor">查看报名情况</p> -->
    </div>

    <div v-html="detail.content" class="detail_content"></div>
    <div>
      <div class="mb10">【家长志愿者招募与积分】</div>
      <a-table size="middle" :columns="columns" :dataSource="data" :key="'table' + tableKey">
        <template slot="status" slot-scope="text, record">
          <template v-if="record.code === 'organize'">
            <div v-if="record.isVolunteer">志愿者</div>
            <div v-if="!record.isVolunteer">-</div>
            <div v-if="record.isVolunteer" style="font-size:12px;color:#999;">(已为您+{{record.volunteerScore}}分)</div>
          </template>
          <template v-if="record.code === 'photo'">
            <div v-if="record.photo && record.photo.content">
              <div>{{ record.photo.content }}</div>
              <div v-if="record.photo && record.photo.score" style="font-size:12px;color:#999;">(已为您+{{record.photo.score}}分)</div>
            </div>
          </template>
          <template v-if="record.code === 'video'">
            <div v-if="record.video && record.video.content">
              <div>{{ record.video.content }}</div>
              <div v-if="record.video && record.video.score" style="font-size:12px;color:#999;">(已为您+{{record.video.score}}分)</div>
            </div>
          </template>
          <template v-if="record.code === 'contribution'">
            <div v-if="record.contribution && record.contribution.content">
              <div>
                <a-icon type="link" class="info_text"/>
                <!-- <span class="info_text cursor">{{ record.contribution.fileName }}</span> -->
                <a :href="'/sysFile/download?url=' + record.contribution.content.replaceAll('\\', '/')">{{ record.contribution.fileName }}</a>
              </div>
              <div v-if="record.contribution && record.contribution.score" style="font-size:12px;color:#999;">(已为您+{{record.contribution.score}}分)</div>
            </div>
          </template>
        </template>
        <template slot="action" slot-scope="text, record">
          <!-- <template v-if="userInfo.role === 'ROLE_VENDOR' && record.code !== 'organize' && moment(detail.endDate).isBefore(moment()) && moment().diff(moment(detail.startDate), 'day') < 3"> -->
          <template v-if="userInfo.role === 'ROLE_VENDOR' && record.code !== 'organize' && moment(detail.endDate).isBefore(moment()) && moment().diff(moment(detail.startDate), 'day') < 3">
            <template v-if="record.code === 'photo'">
              <a-button type="primary" size="small" @click="upload(record)" v-if="record.photo && record.photo.content && !record.photo.score">修改</a-button>
              <a-button type="primary" size="small" @click="upload(record)" v-if="!record.photo">上传</a-button>
            </template>
            <template v-if="record.code === 'video'">
              <a-button type="primary" size="small" @click="upload(record)" v-if="record.video && record.video.content && !record.video.score">修改</a-button>
              <a-button type="primary" size="small" @click="upload(record)" v-if="!record.video">上传</a-button>
            </template>
            <template v-if="record.code === 'contribution'">
              <a-button type="primary" size="small" @click="upload(record)" v-if="record.contribution && record.contribution.fileName && !record.contribution.score">修改</a-button>
              <a-button type="primary" size="small" @click="upload(record)" v-if="!record.contribution">上传</a-button>
            </template>
          </template>
        </template>
      </a-table>
    </div>
    <a-modal v-model="uploadVisible" :title="uploadTitle" @ok="handleUploadOk">
      <template v-if="uploadType === 'photo' || uploadType === 'video'">
        <div><span class="error_text">*</span>百度网盘分享链接：</div>
        <a-input v-model="linkUrl"></a-input>
      </template>
      <template v-else>
        <div><span class="error_text">*</span>请上传附件（word文档）：</div>{{ fileList }}
        <a-upload :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload">
          <a-button> <a-icon type="upload" /> 上传 </a-button>
        </a-upload>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { getCourseDetail, addExpansion, addExpansionFile } from '@/api/config'
export default {
  name: 'intro',
  components: { },
  data () {
    return {
      moment,
      data: [
        {
          id: 1,
          code: 'organize',
          name: '组织秩序（志愿者）',
          personNum: 1,
          task: '负责现场引导、签到、组织合影，维护现场秩序',
          score: '10分'
        },
        {
          id: 2,
          code: 'photo',
          name: '拍照',
          personNum: 1,
          task: '随队拍照，实时分享活动主要照片至会员群。活动后2天内将照片原图，按“精选”和“全部”分类上传到活动详情页“拍照”模块(文件命名为日期+活动主题+拍摄者姓名）',
          score: '5-15分（拍摄分享、上传、精选照片各5分）'
        },
        {
          id: 3,
          code: 'video',
          name: '摄像视频制作',
          personNum: 1,
          task: '现场拍摄并制作后期，实时分享至会员群。活动后2天内将视频原图，按“后期制作”和“全部”分类上传到活动详情页“摄像视频制作”模块(文件命名为日期+活动主题+拍摄者姓名）',
          score: '5-15分（分享、上传、后期制作各5分）'
        },
        {
          id: 4,
          code: 'contribution',
          name: '撰稿',
          personNum: 2,
          task: '新闻稿和感受稿各一篇，分别从总体综合角度、参与体验角度，以新闻稿体例撰写官方活动报道稿件，活动后3天内将新闻稿配图、标注图片作者后上传到活动详情页“撰稿”模块(文件命名为日期+活动主题+新闻稿）。',
          score: '新闻稿10-20分；感受稿10-20分。小朋友稿件采用后20分。'
        }
      ],
      columns: [
        {
          title: '项目',
          dataIndex: 'name',
          width: 100,
          key: 'name',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '人数',
          dataIndex: 'personNum',
          width: 50,
          key: 'personNum'
        },
        {
          title: '任务',
          dataIndex: 'task',
          width: 300,
          key: 'task'
        },
        {
          title: '奖励分',
          dataIndex: 'score',
          width: 100,
          key: 'score',
          scopedSlots: { customRender: 'score' }
        }
      ],
      detail: {},
      uploadType: null,
      uploadVisible: false,
      linkUrl: '',
      userSignDetail: {}, // 当前用户的报名详情
      fileList: [],
      tableKey: 1
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    }),
    uploadTitle () {
      let title = ''
      switch (this.uploadType) {
        case 'photo':
          title = '照片'
          break
        case 'video':
          title = '视频'
          break
        case 'contribution':
          title = '稿件'
          break
        default:
          title = ''
          break
      }
      return title
    }
  },
  watch: {
  },
  async mounted () {
    await this.getDetail()
    // 如果是本人发起的活动或者是参加的会员或志愿者 则可以上传
    if (this.detail.campaignUserInfos.find(t => t.userId === this.userInfo.id) || this.detail.creatorId === this.userInfo.id) {
      this.columns.push({
        title: '上传情况',
        dataIndex: 'status',
        width: 150,
        key: 'status',
        scopedSlots: { customRender: 'status' }
      })
      this.columns.push({
        title: '操作',
        dataIndex: 'action',
        width: 100,
        key: 'action',
        scopedSlots: { customRender: 'action' }
      })
    }
  },
  methods: {
    back () {
      this.$router.go(-1)
    },
    async getDetail () {
      let res = await getCourseDetail({ id: this.$route.query.id })
      if (res.code === 200) {
        this.detail = res.data
        this.userSignDetail = res.data.campaignUserInfos.find(t => !t.userChildId && t.userId === this.userInfo.id)
        this.data[0].volunteerScore = res.data.volunteerScore
        this.data[0].isVolunteer = (this.userSignDetail && this.userSignDetail.type === 'volunteer')
        this.data[1].photo = this.userSignDetail && this.userSignDetail.campaignExpansionInfos.find(t => t.type === 'photo') ? this.userSignDetail.campaignExpansionInfos.find(t => t.type === 'photo') : ''
        this.data[2].video = this.userSignDetail && this.userSignDetail.campaignExpansionInfos.find(t => t.type === 'video') ? this.userSignDetail.campaignExpansionInfos.find(t => t.type === 'video') : ''
        this.data[3].contribution = this.userSignDetail && this.userSignDetail.campaignExpansionInfos.find(t => t.type === 'contribution') ? this.userSignDetail.campaignExpansionInfos.find(t => t.type === 'contribution') : ''
        this.tableKey++
      }
    },
    upload (record) {
      this.uploadType = record.code
      this.linkUrl = ''
      this.uploadVisible = true
    },
    handleRemove (file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload (file) {
      this.fileList = [file]
      // const isLt2M = file.size / 1024 / 1024 < 10
      // if (!isLt2M) {
      //   this.$message.error('文件不能超过10MB!') // 限制文件的大小为不能超过10M
      // }
      // console.info(isLt2M)
      // return isLt2M
      return false
    },
    async handleUploadOk () {
      const { fileList } = this
      this.uploadVisible = false
      const formData = new FormData()
      formData.append('file', fileList[0])
      formData.append('userId', this.userInfo.id)
      formData.append('campaignId', this.detail.id)
      formData.append('type', this.uploadType)
      console.info(formData)
      let params = {
        userId: this.userInfo.id,
        campaignId: this.detail.id,
        type: this.uploadType,
        [this.uploadType]: (this.uploadType === 'photo' || this.uploadType === 'video' ? this.linkUrl : formData)
      }
      // console.info(params)
      let fn
      if (this.uploadType === 'photo' || this.uploadType === 'video') {
        fn = addExpansion
      } else {
        fn = addExpansionFile
        params = formData
      }
      let res = await fn(params)
      if (res.code === 200) {
        this.$message.success('上传成功')
        this.getDetail()
      } else {
        this.$message.error('上传失败')
      }
      this.uploadVisible = false
      this.linkUrl = ''
      this.fileList = []
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '../../styles/var.styl'
.detail_wrap
  padding 20px 30px
  background #fff
</style>
